package api

import (
	"context"
	"fmt"
	"gdmin/config"
	"gdmin/servlet"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/route"
	"github.com/google/uuid"
	"net/url"
	"path/filepath"
)

func FileApi(r *route.RouterGroup) {
	r.POST("/file/update", func(c context.Context, ctx *app.RequestContext) {
		file, err := ctx.FormFile("file")
		if err != nil {
			servlet.FailWithMessage(err.Error(), ctx)

			return
		}
		ext := filepath.Ext(file.Filename)
		path := config.Setting.File.Path
		fileName := uuid.New().String() + ext
		sprintf := fmt.Sprintf(path+"/%s", fileName)
		err = ctx.SaveUploadedFile(file, sprintf)
		if err != nil {
			servlet.FailWithMessage(err.Error(), ctx)
			return
		} else {
			servlet.OkWithData(ctx, map[string]interface{}{
				"file_path": fileName,
			})
		}

	})

	r.GET("/fileAttachment", func(ctx context.Context, c *app.RequestContext) {
		// If you use Chinese, need to encode
		fileName := url.QueryEscape("hertz")
		c.FileAttachment("./file/download/file.txt", fileName)
	})

	r.GET("/file", func(ctx context.Context, c *app.RequestContext) {
		c.File("/Users/zhangsan/temp/go-mico/upload/c654d6d2-1444-457b-9e36-1ec346570d1f.jpg")
	})

}
